<!-- 意见反馈 -->
<template>
  <div class="grid" ref="feedback">
    <div class="col-12">
      <CommonHeaderToolBar></CommonHeaderToolBar>
    </div>
    <!-- 左侧导航栏 -->
    <StickyPanel class="col-2 mt-4" top="40px" :dom="feedback">
      <template #content>
        <LeftMenu/>
      </template>
    </StickyPanel>
    <!-- 提交反馈信息 -->
    <div class="grid col-10 p-0">
      <!-- 用户反馈 -->
      <div class="grid col-8 p-5" style="margin-left: 10%;">
        <div class="col-12 justify-content-center">
          <!-- 标题 -->
          <div class="flex justify-content-center mt-5">
            <InputText v-model="publish.title"
                       style="width: 50vw;"
                       placeholder="简要概括下你要反馈啥子"/>
          </div>
          <!-- 内容 -->
          <div class="flex justify-content-center mt-5">
            <VditorEditor @change="vditorEditorChangeHandler"
                          :editor-value="publish.content"
                          :width="'50vw'"
                          :outline="false"
                          placeholder="好好详细说说你要反馈的内容，给我康康!!"/>
          </div>
          <!-- 提交反馈信息 -->
          <div class="flex justify-content-center mt-5">
            <Button class="p-button-text"
                    :disabled="disabledSubmit"
                    @click="commitFeedback"
                    label="提交提交~"
                    style="width: 50vw;"></Button>
          </div>
        </div>
      </div>
    </div>
    <!-- 反馈的信息列表 -->
    <div class="col-offset-2 col-9 flex justify-content-center p-5">
      <div class="feedback w-screen">
        <div class="grid mt-0 feedback-container" v-for="(item, index) of feedbacks" :key="index">
          <div class="lg:col-2 md:col-3 sm:col-4 align-items-center align-self-center">
            <!-- 用户信息 -->
            <div class="grid">
              <div class="flex col-12 justify-content-center align-items-center">
                <Avatar :image="item.avatar"
                        class="m-huge-avatar"
                        shape="circle"/>
              </div>
              <div class="flex col-12 justify-content-center align-items-center pt-5">
                {{ item.username }}
              </div>
            </div>
          </div>
          <!-- 反馈标题以及内容 -->
          <div class="lg:col-10 md:col-9 sm:col-8 grid flex align-items-stretch flex-wrap">
            <div class="feedback-title col-12 border-bottom-1">
              <div>
                <h2>
                  {{ item.title }}
                </h2>
                <span class="feedback-date">
                  {{ item.date }}
                </span>
              </div>
            </div>
            <div class="feedback-content col-12">
              <div :id="`vditorPreview${index}`" class="vditor-reset"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
/** JS */
import {ref, Ref, reactive, onMounted, nextTick, watch} from 'vue';
import {FeedbackCommitEntity, FeedbackResponseEntity} from '@/interface/feedback/entity/FeedbackEntityInterface';
import {FeedbackService, Paging} from '@/utils/ApiRequest';
/** 组件 */
import Avatar from 'primevue/avatar';
import CommonHeaderToolBar from '@/components/toolbar/CommonHeaderToolBar.vue';
import VditorEditor from '@/components/editor/VditorEditor.vue';
import StickyPanel from '@/components/panel/StickyPanel.vue';
import LeftMenu from '@/components/menu/LeftMenu.vue';
import Vditor from 'vditor';
import {encrypt, decrypt} from '@/utils/PakoUtils';
import toast from "@/utils/Toast";


/** 数据初始化 */
const feedbackService = new FeedbackService();
/** 元素钩子 */
const feedback = ref(null);
/** 提交反馈 */
const publish: FeedbackCommitEntity = reactive({
  title: '',
  content: ''
}), disabledSubmit = ref(true);

watch(publish, (n) => {
  disabledSubmit.value = n.content.trim() === '' || n.title.trim() === '';
}, {deep: true})

const vditorEditorChangeHandler = ({md}) => {
  publish.content = md;
}, commitFeedback = async () => {
  publish.content = encrypt(publish.content);
  // 加密后的空字符串
  if (publish.content.trim() !== 'H4sIAAAAAAAAAwMAAAAAAAAAAAA=') {
    let res = await feedbackService.commit(publish);
    if (res && res.code == 0) {
      toast.success('已经收到啦~', res.msg, 3000);
      publish.title = '';
      publish.content = '';
    }
  }
};
/** 获取反馈列表 */
const paging: Ref<Paging> = ref({
      page: 0,
      limit: 10
    }),
    feedbacks: Ref<FeedbackResponseEntity[]> = ref([]),
    getFeedbackList = async (paging: Paging) => {
      let res = await feedbackService.list(paging);
      if (res) {
        feedbacks.value.push(...res.data);
        await nextTick(() => {
          let arr = feedbacks.value.map(feedback => {
            feedback.content = decodeURIComponent(decrypt(feedback.content));
            let date = new Date(feedback.date);
            let year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate(), hour = date.getHours(),
                minute = date.getMinutes();
            feedback.date = `${year}/${month}/${day} ${hour}:${minute}`;
            return feedback;
          });
          arr.forEach((feedback, index) => {
            const preview: any = document.getElementById(`vditorPreview${index}`);
            Vditor.preview(preview, feedback.content, {
              mode: "dark",
              anchor: 2,
              cdn: 'https://cdn.yeziji.xyz/vditor@3.8.15',
              hljs: {
                style: 'native',
                lineNumber: true
              },
              after: () => {
                // 更新图片大小的细节
                let imgs = document.getElementsByTagName('img');
                let pattern = /{{\d+,(\s)*\d+}}/;
                if (imgs && imgs.length > 0) {
                  for (let img of imgs) {
                    let imgParentEle = img.parentElement;
                    if (imgParentEle) {
                      let innerHtml = imgParentEle.innerHTML
                      if (pattern.test(innerHtml)) {
                        let matchs = innerHtml.match(pattern);
                        if (matchs) {
                          for (let match of matchs) {
                            if (match.trim() !== '') {
                              // 获取高度进行筛选过滤
                              let matchStr = match.replace('{{', '').replace('}}', ''), matchArr = matchStr.split(',');
                              let height = matchArr[0], width = matchArr[1];
                              // 赋值 style
                              img.style.height = `${height}px`;
                              img.style.width = `${width}px`;
                              // 清除 {{number, number}}
                              imgParentEle.innerHTML = imgParentEle.innerHTML.replace(match, '');
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            })
          });
        })
      }
    }


onMounted(() => {
  getFeedbackList(paging.value);
})
</script>

<style lang="less" scoped>
.feedback {
  background-color: white;
  border-radius: 5px;
  box-shadow: 2px 2px 5px #969696,
    -2px -2px 5px #969696;
  padding: 5px;
}

.feedback-date {
  font-size: 14px;
  color: var(--text-gray-color);
}

.feedback-container {
  //border-bottom: 1px darkcyan dotted !important;
}
</style>
